package sample;

import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.DdmPreferences;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.Log;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;

import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable {
	public ListView<String> devicesList;
	public ObservableList<String> list = FXCollections.observableArrayList();
	private static final String TAG = "Controller";

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		DdmPreferences.setLogLevel(Log.LogLevel.VERBOSE.getStringValue());
		devicesList.setItems(list);
		new AdbThread().start();
	}

	private class AdbThread extends Thread implements AndroidDebugBridge.IDebugBridgeChangeListener, AndroidDebugBridge.IDeviceChangeListener {

		@Override
		public void run() {
			AndroidDebugBridge.init(false);
			AndroidDebugBridge.createBridge(getAdbPath(), true);
			AndroidDebugBridge.addDebugBridgeChangeListener(this);
			AndroidDebugBridge.addDeviceChangeListener(this);
		}

		@Override
		public void bridgeChanged(AndroidDebugBridge bridge) {
			Log.i(TAG, "bridge连接:" + AndroidDebugBridge.getSocketAddress());
		}

		@Override
		public void deviceConnected(IDevice device) {
			Platform.runLater(() -> {
				list.add(device.getSerialNumber() + "\n在线状态:" + device.isOnline());
			});
		}

		@Override
		public void deviceDisconnected(IDevice device) {

		}

		@Override
		public void deviceChanged(IDevice device, int changeMask) {

		}
	}

	public static String getAdbPath() {
		String adbPath = System.getenv("ANDROID_HOME");
		if (adbPath != null) {
			adbPath += File.separator + "platform-tools";
		} else {
			throw new RuntimeException("没有找到ANDROID_HOME环境变量");
		}
		adbPath += File.separator + "adb";
		return adbPath;
	}
}
